import { _decorator, Color, Component, director, Label, Node, Sprite, v2, v3, Vec3 } from 'cc';
import { WorldCamera } from '../common/WorldCamera';
import WorldManager from '../common/WorldManager';
import { UserInfo } from '../common/UserInfo';
import { WorldController } from '../common/WorldController';
import { UIManager } from '../common/UIManager';
const { ccclass, property } = _decorator;

@ccclass('Compass')
export class Compass extends Component {
    @property(Sprite)
    sprite:Sprite
    @property(Node)
    arrow:Node
    @property(Node)
    bg:Node
    @property(Label)
    desc:Label

    sceneName:string

    distance:number = 0

    start() {
        this.node.on(Node.EventType.TOUCH_END, this.onClick, this)

        this.sceneName = director.getScene().name
        if(this.sceneName == 'village'){
            this.bg.position = v3(0, 0, 0)
            this.arrow.position = v3(1000, 0, 0)
            this.desc.node.position = v3(1000, 0, 0)
        }
    }

    update(deltaTime: number) {
        if(this.sceneName == 'village'){
            return
        }

        let cameraPos = WorldCamera.instance.node.worldPosition

        let x = UserInfo.instance.villageData.xId
        let y = UserInfo.instance.villageData.yId
        let cityPos = WorldManager.instance.getWorldPostionByXY(v2(x, y))

        this.setData(cityPos, cameraPos)
    }

    setData(cityPos:Vec3, cameraPos:Vec3){
        let dir = v3(0, 0, 0)
        Vec3.subtract(dir , cityPos, cameraPos)

        let hu = Math.atan2(dir.y, dir.x)
        // 角度= 弧度 * 180 / pi
        // 弧度= 角度 / 180 * pi
        let angle = hu * 180 / Math.PI

        this.arrow.eulerAngles = v3(0, 0, angle)


        this.distance = dir.length()
      
        this.distance = this.distance / 1000
        this.distance = Math.floor(this.distance * 10) / 10
        this.desc.string = this.distance  + ' KM'

        if(this.distance > 0.2){
            this.bg.position = v3(1000, 0, 0)
            this.arrow.position = v3(0, 0, 0)
            this.desc.node.position = v3(0, 0, 0)
        } else{
            this.bg.position = v3(0, 0, 0)
            this.arrow.position = v3(1000, 0, 0)
            this.desc.node.position = v3(1000, 0, 0)
        }
    }

    onClick(){
        if(this.sceneName == 'village'){
            UIManager.instance.loadScene('world')
        } else {
            if(this.distance > 0.2){
                WorldController.instance.goHome()
            } else {
                UIManager.instance.loadScene('village')
            }
        }

        
    }
}


